package com.viethp.mt.activities;

import java.util.ArrayList;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.viethp.mt.common.CommonHelper;
import com.viethp.mt.common.GlobalVariables;
import com.viethp.mt.customactivities.ATabNearByGroup;
import com.viethp.mt.mapoverlay.MyItemizedOverlay;
import com.viethp.mt.objects.GetPostListResponse;
import com.viethp.mt.objects.OItem;

public class AGroupMap extends MapActivity implements OnClickListener, Runnable {

	// private static final String ITEM_ID = "id";
	// private static final String ITEM_USER_ID = "user_id";
	// private static final String ITEM_USERNAME = "username";
	// private static final String ITEM_TITLE = "title";
	// private static final String ITEM_DESCRIPTION = "description";
	// private static final String ITEM_EXP = "expired";
	// private static final String ITEM_PRICE = "price";
	// private static final String ITEM_LON = "longitude";
	// private static final String ITEM_LAT = "latitude";
	// private static final String ITEM_IMG_LINK = "imgLink";

	MapController mControl;
	GeoPoint GeoP;
	MapView mapV;
	private Button btn_back, btn_more, btn_refesh;
	private ProgressDialog progressDialog;
	private Thread progressThread;

	private List<Overlay> mapOverlays;
	private Drawable items;
	private MyItemizedOverlay itemizedOverlay;
	private int totaPages, post_category;
	private int pages;

	private ArrayList<OItem> list_Oitems;
	private ArrayList<OverlayItem> list_OLitems;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);

		mapV = (MapView) findViewById(R.id.mapView);
		mapV.displayZoomControls(true);
		mapV.setBuiltInZoomControls(true);

		mapV.setTraffic(true);

		initComponents();
		setOnClickListener();
		setMap();
		// setWantItems();
		initData();
	}

	public void setMap() {
		if (CommonHelper.getPosition(getParent()).getLon().equals("")
				|| CommonHelper.getPosition(getParent()).getLat().equals("")) {
			GeoP = new GeoPoint((int) (GlobalVariables.lat * 1E6),
					(int) (GlobalVariables.lon * 1E6));
		} else
			GeoP = new GeoPoint((int) (Double.parseDouble(CommonHelper
					.getPosition(getParent()).getLat()) * 1E6),
					(int) (Double.parseDouble(CommonHelper.getPosition(
							getParent()).getLon()) * 1E6));

		mControl = mapV.getController();
		mControl.animateTo(GeoP);
		mControl.setZoom(15);
		// mapV.invalidate();
	}

	public void initComponents() {
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_more = (Button) findViewById(R.id.btn_more);
		btn_refesh = (Button) findViewById(R.id.btn_refesh);
		btn_refesh.setVisibility(View.INVISIBLE);
		
		list_Oitems = new ArrayList<OItem>();
		list_OLitems = new ArrayList<OverlayItem>();
		
		totaPages = 1;
		pages = 1;
		post_category = 0;
	}

	public void setOnClickListener() {
		btn_back.setOnClickListener(this);
		btn_more.setOnClickListener(this);
		btn_refesh.setOnClickListener(this);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	public void setWantItems() {
		int Length = list_OLitems.size();
		Log.v("len", "" + Length);
		mapOverlays = mapV.getOverlays();
		items = this.getResources().getDrawable(R.drawable.pin_want);
		itemizedOverlay = new MyItemizedOverlay(items, mapV);
		for (int i = 0; i < Length; i++) {
			OverlayItem ovi = list_OLitems.get(i);
			itemizedOverlay.addOverlay(ovi);
			Log.v("set", "" + ovi.getPoint().getLatitudeE6() + " "
					+ ovi.getPoint().getLongitudeE6());
		}
		mapOverlays.add(itemizedOverlay);
		mapV.postInvalidate();
	}

	public void convertData() {
		for (int i = 0; i < list_Oitems.size(); i++) {
			OItem oi = list_Oitems.get(i);
			if (oi.getDescription().equals(""))
				oi.setDescription("No description");
			OverlayItem ovi = new OverlayItem(new GeoPoint(
					(int) (oi.getLat() * 1E6), (int) (oi.getLon() * 1E6)),
					oi.getTitle() + "haphuocviet" + oi.getPrice()
							+ "haphuocviet" + oi.getImgLink() + "haphuocviet"
							+ oi.getExp() + "haphuocviet" + oi.getDescription()
							+ "haphuocviet" + oi.getMaxBudget() + "haphuocviet"
							+ oi.getTotalBidder(), String.valueOf(oi.getId()));
			list_OLitems.add(ovi);
			Log.v("cv", "" + i);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			ATabNearByGroup.group.back();
			break;
		case R.id.btn_more:
			if (pages < totaPages) {
				pages++;
				Log.d("total1", ""+totaPages);
				Log.d("page1", ""+pages);
				initData();
			}
			break;
		case R.id.btn_refesh:
			pages = 1;
			list_Oitems.removeAll(list_Oitems);
			initData();
		}

	}

	public void initData() {

		if (CommonHelper.isNetworkAvailable(this)) {
			startCallService();
		} else {
			CommonHelper.showWarning(this, getString(R.string.netstate));
		}

	}

	private void release() {
		if (progressThread != null && !progressThread.isInterrupted()) {
			progressThread.interrupt();
			progressThread = null;
		}
	}

	private void startCallService() {
		if (progressThread == null) {
			progressDialog = ProgressDialog.show(getParent(), "",
					"Please wait...", true);
			progressDialog.setCancelable(false);
			progressThread = new Thread(AGroupMap.this);
			progressThread.start();
		}
	}

	private Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			release();
			if (msg.obj != null) {
				GetPostListResponse response = (GetPostListResponse) msg.obj;
				if (response.getErrorCode() != null) {
					CommonHelper.showWarning(getParent(), response
							.getErrorCode().getErrMsg());
				} else {
					pages = response.getPage();
					totaPages = response.getTotalPage();
					Log.d("total", ""+totaPages);
					Log.d("page", ""+pages);
					ArrayList<OItem> OitemArr = response.getPostArray();
					for (OItem oi : OitemArr) {
						list_Oitems.add(oi);
					}
				}
				
				if (pages == totaPages) {
					btn_more.setVisibility(View.INVISIBLE);
					btn_refesh.setVisibility(View.VISIBLE);
				} else {
					btn_more.setVisibility(View.VISIBLE);
					btn_refesh.setVisibility(View.INVISIBLE);
				}
				convertData();
				setWantItems();
				mapV.postInvalidate();
			} else {
				CommonHelper.showWarning(getParent(),
						getString(R.string.loaddatastate));

			}

		};
	};

	// public int callService(){
	// demoData(10);
	// convertData();
	//
	// return GlobalVariables.ReOK;
	// }

	public void run() {
		Message message = new Message();
		message.obj = callService();
		handler.sendMessage(message);

	}

	public GetPostListResponse callService() {
		SoapObject userRequest = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_GET_POST_LIST);
		userRequest.addProperty("user_id", CommonHelper.getUserLogin(this)
				.getId());
		userRequest.addProperty("category_id", post_category);
		userRequest.addProperty("page", pages);
		Log.d("page2", ""+pages);

		SoapObject request = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_GET_POST_LIST);
		request.addProperty(GlobalVariables.WS_METHOD_GET_POST_LIST,
				userRequest);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		HttpTransportSE androidHttpTransport = new HttpTransportSE(
				GlobalVariables.WS_ENDPOINT,
				GlobalVariables.WS_CONNECTTION_TIME_OUT);
		SoapObject results = null;
		try {
			androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
					+ GlobalVariables.WS_METHOD_GET_POST_LIST, envelope);
		} catch (Exception e) {
			try {
				androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
						+ GlobalVariables.WS_METHOD_GET_POST_LIST, envelope);
			} catch (Exception e1) {
				e1.printStackTrace();
				return null;

			}
		}
		try {
			results = (SoapObject) envelope.getResponse();
		} catch (SoapFault ex3) {
			ex3.printStackTrace();
			return null;
		}
		return new GetPostListResponse(results);
	}

}
